package com.demo.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.api.CheckJs;
import com.demo.api.MediaApi;
import com.demo.api.MsgCustomApi;
import com.demo.api.OutKfMsg;
import com.demo.api.OutKfXmlBuilder;
import com.demo.api.PushTemp;
import com.demo.api.Temaple;
import com.demo.util.AmrToMp3;
import com.demo.util.PropertiesHelper;
import com.demo.util.Upload;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.JFinal;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.weixin.sdk.api.AccessToken;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.jfinal.WeixinController;
import com.jfinal.weixin.sdk.kit.ParaMap;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutMsg;
import com.jfinal.weixin.sdk.msg.out.OutNewsMsg;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;

import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.log4j.Logger;

import com.demo.index.WxInterceptor;
import com.demo.msg.WxMessage;

/**
 * 将此 DemoController 在YourJFinalConfig 中注册路由， 并设置好weixin开发者中心的 URL 与 token ，使
 * URL 指向该 DemoController 继承自父类 WeixinController 的 index
 * 方法即可直接运行看效果，在此基础之上修改相关的方法即可进行实际项目开发
 */
@ClearInterceptor()
public class DemosController extends WeixinController {

	private static final String helpStr = "您想制作吗？\n"
			+ "【1】发送字母N或点击菜单开始按钮开始制作\n【2】发送图片和文字\n【3】发送字母S结束制作";
//	private static final String starts = "好的，开始制作！请先选择模板并确定然后发送图片、文字给我们，我们会按照您发送的顺序"
//			+ "依次记录。\n\n【提示】 如果你没有找到底部的输入框，请先点击左下角键盘图标。如果要结束制作，请发送字母S；"
//			+ "发送减号“-”可以取消制作";
	private static final String starts = "好的，开始制作！请先选择模板！";
	private static final String err = "您有任务正在进行中！\n" + "【任务】微文制作\n"
			+ "【提示】只有取消当前任务才可以开始新的任务。您可以发送减号“-”取消当前任务。";
	private static final String end = "好的，起个标题吧";
	private static final String ends = "您还没有开始制作喔，发送字母N或者点击菜单开始按钮即可开始";
	private static final String enda = "当前没有任务可以取消";
	private static final String remov = "成功取消当前任务：\n制作";
	private static final String help = "我要联系客服";

	private static String filePath = "";
	private static String url = "";
	private static String AppSecret = "";
	private static String AppId = "";
	/**
	 * 判断filePhth路径中是否存在该文件夹，不存在则创建该文件夹 创建成功则返回True
	 * 
	 * @param filePhth
	 * @return
	 **/
	static {
		Properties r = PropertiesHelper.loadProperty("/weixin.properties");
		if (!r.isEmpty()) {
			try {
				filePath = r.getProperty("filePath");
				url = r.getProperty("wxmediaUrl");
				AppSecret = r.getProperty("AppSecret");
				AppId = r.getProperty("AppId");

				if (!url.endsWith("/"))
					url = url + "/";
				filePath = JFinal.me().getContextPath() + "/" + filePath;
			} catch (Exception e) {
				Logger.getLogger(Upload.class).error("无法读取参数", e);
			}
		} else {
			Logger.getLogger(Upload.class).error("无法读取 weixin.properties");
		}
	}

	// 保存用户制作信息
	// fromuser+"title"： 标题信息 fromuser+"template"： 模板信息 fromuser : 内容信息
	// fromuser+"pic" 首页图片 内容：fromuser+" content"
	public static HashMap extMaps = new HashMap();

	/**
	 * 实现父类抽方法，处理文本消息 本例子中根据消息中的不同文本内容分别做出了不同的响应，同时也是为了测试 jfinal weixin
	 * sdk的基本功能： 本方法仅测试了 OutTextMsg、OutNewsMsg、OutMusicMsg 三种类型的OutMsg，
	 * 其它类型的消息会在随后的方法中进行测试
	 */
	protected void processInTextMsg(InTextMsg inTextMsg) {
		String msgContent = inTextMsg.getContent().trim();
		String fromuser = inTextMsg.getFromUserName();
		String title="经典魔术";
		String nr="每次看别人表演魔术都觉得好新奇，其实你也可以做到！看完自己做一个，找朋友测试一下吧......那画面肯定有趣!";
		String picurl="http://hxkjoa.cn/img/lq.jpg";
		String url="http://mp.weixin.qq.com/s?__biz=MzAxODIwNDc2MQ==&mid=207536458&idx=1&sn=148f91a0ccd16723233d6663677aa9d6#rd";
		 if ("魔术".equals(msgContent)) {
				OutNewsMsg outMsg = new OutNewsMsg(inTextMsg);
				outMsg.addNews(title, nr, picurl, url);
				render(outMsg);
				
		 } else if (msgContent.equalsIgnoreCase("f")) {
				// 查询
				findAll(inTextMsg, fromuser);
		 }else if (msgContent.equalsIgnoreCase("我的")) {
				// 查询
				findAll(inTextMsg, fromuser);
		 }
		 else {
				OutTextMsg outMsg = new OutTextMsg(inTextMsg);
				outMsg.setContent("欢迎关注超级朋友圈，回复“魔术”揭晓答案。");
				render(outMsg);
		 }
		 
	
/*
		String msgContent = inTextMsg.getContent().trim();
		String msgType = inTextMsg.getMsgType();
		String fromuser = inTextMsg.getFromUserName();

		if (CacheKit.get("extMap", fromuser) != null) {
			// 如果制作信息存在,此用户 多次点击N输出错误信息，如果不存在输入开始信息 并保存用户信息信息
			if ("n".equalsIgnoreCase(msgContent)) {
				// setContent(msgType,msgContent,fromuser);
				OutTextMsg outMsg = new OutTextMsg(inTextMsg);
				outMsg.setContent(err);
				render(outMsg);
				// 消息制作 取消；
			} else if ("-".equals(msgContent)) {
				removeAllMap(fromuser);
				OutTextMsg outMsg = new OutTextMsg(inTextMsg);
				outMsg.setContent(remov);
				render(outMsg);
				// 消息制作 标题；
			} else if ("s".equalsIgnoreCase(msgContent)) {
				if (CacheKit.get("extMap", fromuser + "template") != null) {
					CacheKit.put("extMap", fromuser + "title", " ");
					OutTextMsg outMsg = new OutTextMsg(inTextMsg);
					outMsg.setContent(end);
					render(outMsg);
				} else {
					// 模板 选择
					rendermb(inTextMsg, fromuser, "1");
				}
			} else {
				// 消息制作 标题
				if (CacheKit.get("extMap", fromuser + "title") != null
						&& CacheKit.get("extMap", fromuser + "template") != null) {
					// 标题制作；
					System.out.println("====title=======" + msgContent);
					CacheKit.put("extMap", fromuser + "title", msgContent);
					// 调用模板使用
					String title = CacheKit.get("extMap", fromuser + "title")
							.toString();
					
					 * OutTextMsg outMsg = new OutTextMsg(inTextMsg);
					 * outMsg.setContent("收到标题：" + title + "    ");
					 * render(outMsg);
					 
					savemsg(fromuser);
					//
					// saveContent(msgType, msgContent, fromuser, inTextMsg,
					// null, null);
				} else if (CacheKit.get("extMap", fromuser + "title") == null
						&& CacheKit.get("extMap", fromuser + "template") != null) {
					saveContent(msgType, msgContent, fromuser, inTextMsg);
				} else if (CacheKit.get("extMap", fromuser + "title") == null
						&& CacheKit.get("extMap", fromuser + "template") == null) {
					rendermb(inTextMsg, fromuser, "1");
				}
			}

			// 消息制作；
		} else {
			// 如果制作信息里面没有此用户 多次点击s输出错误信息，如果不存在输入开始信息 并保存用户信息信息
			if ("n".equalsIgnoreCase(msgContent)) {
	//			CacheKit.put("extMap", fromuser, fromuser);
				rendermb(inTextMsg, fromuser, "0");
			} else if ("s".equalsIgnoreCase(msgContent)) {
				OutTextMsg outMsg = new OutTextMsg(inTextMsg);
				outMsg.setContent(ends);
				render(outMsg);
			} else if ("-".equals(msgContent)) {
				OutTextMsg outMsg = new OutTextMsg(inTextMsg);
				outMsg.setContent(enda);
				render(outMsg);
			} else {
				OutTextMsg outMsg = new OutTextMsg(inTextMsg);
				outMsg.setContent(helpStr);
				render(outMsg);

			}

		}*/
	}


	
	/**
	 * 实现父类抽方法，处理图片消息
	 */
	protected void processInImageMsg(InImageMsg inImageMsg) {
		String picurl = inImageMsg.getPicUrl();
		String msgType = inImageMsg.getMsgType();
		String fromuser = inImageMsg.getFromUserName();
		System.out.println("=================" + inImageMsg.getMediaId());
		System.out.println("=================" + inImageMsg.getPicUrl());

		String mediaId = inImageMsg.getMediaId();
		// 如果 map里存在此用户证明开始制作 先保存图片数据数据
		if (CacheKit.get("extMap", fromuser) != null) {
			saveImg(mediaId, msgType, fromuser, inImageMsg);
		} else {
			OutTextMsg outMsg = new OutTextMsg(inImageMsg);
			outMsg.setContent(helpStr);
			render(outMsg);
		}
	}

	/**
	 * 实现父类抽方法，处理语音消息
	 */
	protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
		String msgType = inVoiceMsg.getMsgType();
		String fromuser = inVoiceMsg.getFromUserName();
		String mediaId = inVoiceMsg.getMediaId();
		// 如果 map里存在此用户证明开始制作 先保存图片数据数据
		if (CacheKit.get("extMap", fromuser) != null) {
			saveVoice(mediaId, msgType, fromuser, inVoiceMsg);
		} else {
			OutTextMsg outMsg = new OutTextMsg(inVoiceMsg);
			outMsg.setContent(helpStr);
			render(outMsg);
		}
	}

	private void saveImg(String mediaId, String msgType, String fromuser,
			InImageMsg inImageMsg) {
		String accessToken = AccessTokenApi.getAccessToken().getAccessToken();
		String msgtype = inImageMsg.getMsgType();
		System.out.println("=============img msgtype==========" + msgtype);

		String picurl = inImageMsg.getPicUrl();
		String file = MediaApi.getMedia(mediaId, msgtype);
		System.out.println("=============img src==========" + file);

		// 图片预览显示路径
		if (CacheKit.get("extMap", fromuser + "pic") == null) {
			CacheKit.put("extMap", fromuser + "pic",
					file.substring(1, file.length()));
		}
		// 修改样式请直接修改li
		String img = " <img src='" + file + "' alt=/>";
		saveContent(msgType, img, fromuser, inImageMsg);
	}

	private void saveVoice(String mediaId, String msgType, String fromuser,
			InVoiceMsg inVoiceMsg) {
		String accessToken = AccessTokenApi.getAccessToken().getAccessToken();
		String msgtype = inVoiceMsg.getMsgType();
		System.out.println("accessToken==" + accessToken);
		System.out.println("accessToken==" + inVoiceMsg.getMsgId());
		String file = MediaApi.getMedia(mediaId, msgtype);
		String filea = "";
		try {
			filea = AmrToMp3.armtomp3(
					PathKit.getWebRootPath() + file,
					PathKit.getWebRootPath()
							+ file.substring(0, file.length() - 4) + ".mp3");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		file = file.substring(0, file.length() - 4) + ".mp3";
		System.out.println("filea===============" + filea);
		String voice = "<audio controls='controls' src='" + file
				+ "'  height='200' width='200'></audio>";
		saveContent(msgType, voice, fromuser, inVoiceMsg);
	}

	/**
	 * 实现父类抽方法，处理视频消息
	 */
	protected void processInVideoMsg(InVideoMsg inVideoMsg) {
		/*
		 * 腾讯 api 有 bug，无法回复视频消息，暂时回复文本消息代码测试 OutVideoMsg outMsg = new
		 * OutVideoMsg(inVideoMsg); outMsg.setTitle("OutVideoMsg 发送");
		 * outMsg.setDescription("刚刚发来的视频再发回去"); // 将刚发过来的视频再发回去，经测试证明是腾讯官方的 api
		 * 有 bug，待 api bug 却除后再试 outMsg.setMediaId(inVideoMsg.getMediaId());
		 * render(outMsg);
		 */
		OutTextMsg outMsg = new OutTextMsg(inVideoMsg);
		outMsg.setContent("\t视频消息已成功接收，该视频的 mediaId 为: "
				+ inVideoMsg.getMediaId());
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理地址位置消息
	 */
	protected void processInLocationMsg(InLocationMsg inLocationMsg) {
		OutTextMsg outMsg = new OutTextMsg(inLocationMsg);
		outMsg.setContent("已收到地理位置消息:" + "\nlocation_X = "
				+ inLocationMsg.getLocation_X() + "\nlocation_Y = "
				+ inLocationMsg.getLocation_Y() + "\nscale = "
				+ inLocationMsg.getScale() + "\nlabel = "
				+ inLocationMsg.getLabel());
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理链接消息 特别注意：测试时需要发送我的收藏中的曾经收藏过的图文消息，直接发送链接地址会当做文本消息来发送
	 */
	protected void processInLinkMsg(InLinkMsg inLinkMsg) {
		OutNewsMsg outMsg = new OutNewsMsg(inLinkMsg);
		outMsg.addNews(
				"链接消息已成功接收",
				"",
				"http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq1ibBkhSA1BibMuMxLuHIvUfiaGsK7CC4kIzeh178IYSHbYQ5eg9tVxgEcbegAu22Qhwgl5IhZFWWXUw/0",
				inLinkMsg.getUrl());
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理关注/取消关注消息
	 */
	protected void processInFollowEvent(InFollowEvent inFollowEvent) {
		OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
		String openid=outMsg.getFromUserName();
		
		outMsg.setContent("欢迎关注超级朋友圈，你可以点击“开始制作”按钮制作图文。");
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理扫描带参数二维码事件
	 */
	protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
		OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
		outMsg.setContent("processInQrCodeEvent() 方法测试成功");
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理上报地理位置事件
	 */
	protected void processInLocationEvent(InLocationEvent inLocationEvent) {
		OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
		outMsg.setContent("processInLocationEvent() 方法测试成功");
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理自定义菜单事件
	 */
	protected void processInMenuEvent(InMenuEvent inMenuEvent) {
		String event = inMenuEvent.getEvent();

		String fromuser = inMenuEvent.getFromUserName();
		String key = inMenuEvent.getEventKey();
		// OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
		// outMsg.setContent("processInMenuEvent() 方法测试成功");
		// render(outMsg);
		System.out.println("inMenuEvent  ===" + event);
		if (event.equals("VIEW")) {
			renderNull();
			System.out.println("inMenuEvent  ===" + event);
			return;
		}
	
//		if (CacheKit.get("extMap", fromuser) != null) {
			// 如果制作信息里面存在此用户 多次点击N输出错误信息，如果不存在输入开始信息 并保存用户信息信息
			if ("n".equalsIgnoreCase(key)) {
				// setContent(msgType,msgContent,fromuser);
				OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
				outMsg.setContent(err);
				render(outMsg);
			} else if ("help".equalsIgnoreCase(key)) {
				OutKfMsg outMsg = new OutKfMsg(inMenuEvent);
				outMsg.setMsgType("transfer_customer_service");
				renderkf(outMsg);
			} else if ("s".equalsIgnoreCase(key)) {
				if (CacheKit.get("extMap", fromuser + "template") != null) {
					CacheKit.put("extMap", fromuser + "title", " ");
					OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
					outMsg.setContent(end);
					render(outMsg);
				} else {
					CacheKit.put("extMap", fromuser, fromuser);
					rendermb(inMenuEvent, fromuser, "1");
				}

			} else if (key.equalsIgnoreCase("f")) {
				// 查询
				findAll(inMenuEvent, fromuser);
			} else if ("-".equals(key)) {
				removeAllMap(fromuser);
				OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
				outMsg.setContent("成功取消当前任务：\n微文制作");
				render(outMsg);
			} else {
				OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
				outMsg.setContent(helpStr);
				render(outMsg);
			}
//		} else {
//			// 如果制作信息里面没有此用户 多次点击s输出错误信息，如果不存在输入开始信息 并保存用户信息信息
//			if ("n".equalsIgnoreCase(key)) {
//			//	CacheKit.put("extMap", fromuser, fromuser);
//				rendermb(inMenuEvent, fromuser, "0");
//			} else if ("help".equalsIgnoreCase(key)) {
//				OutKfMsg outMsg = new OutKfMsg(inMenuEvent);
//				outMsg.setMsgType("transfer_customer_service");
//				renderkf(outMsg);
//			} else if ("s".equalsIgnoreCase(key)) {
//				OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
//				outMsg.setContent(ends);
//				render(outMsg);
//			} else if ("-".equals(key)) {
//				OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
//				outMsg.setContent(enda);
//				render(outMsg);
//			} else if (key.equalsIgnoreCase("f")) {
//				findAll(inMenuEvent, fromuser);
//			} else {
//				OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
//				outMsg.setContent(helpStr);
//				render(outMsg);
//			}
//		}
	}

	/**
	 * 实现父类抽方法，处理接收语音识别结果
	 */
	protected void processInSpeechRecognitionResults(
			InSpeechRecognitionResults inSpeechRecognitionResults) {
		OutTextMsg outMsg = new OutTextMsg(inSpeechRecognitionResults);
		outMsg.setContent("processInSpeechRecognitionResults() 方法测试成功");
		render(outMsg);
	}

	// /**
	// * 获取公众号菜单
	// */
	// public void getMenu() {
	// ApiResult apiResult = MenuApi.getMenu();
	// if (apiResult.isSucceed())
	// renderText(apiResult.getJson());
	// else
	// renderText(apiResult.getErrorMsg());
	// }

	/**
	 * 保存数据
	 */
	private void saveContent(String msgType, String content, String fromuser,
			Object obj) {
	
		String type = "";
		String types = "";
		String msgtype = "";
		if (StringKit.notNull(CacheKit.get("extMap", fromuser + "template"))) {
			type = CacheKit.get("extMap", fromuser + "template").toString();

		}
		if (StringKit.notNull(CacheKit.get("extMap", fromuser + "types"))) {
			types = CacheKit.get("extMap", fromuser + "types").toString();
		}
		String re = "";
		// 模板步骤
		List<Record> mbtypelist = mbsx(type);
		int n = 0;
		System.out.println("=========mbtypelist.size()========"
				+ mbtypelist.size());

		if (msgType.equals("text")) {
			msgtype = "text";
		}
		if (msgType.equals("image")) {
			msgtype = "image";
		}
		if (msgType.equals("voice")) {
			msgtype = "voice";
		}
		if (mbtypelist.size() > 0) {
			n = Integer.parseInt(types) + 1;
			CacheKit.put("extMap", fromuser + "types", n);
			System.out.println("=========n=========" + n);
			if (n < mbtypelist.size()) {
				re = "请输入：" + mbtypelist.get(n).get("mbsxmc");
				System.out.println("=========re=========" + re);

			} else if (n == mbtypelist.size()) {
				CacheKit.put("extMap", fromuser + "title", " ");
				re = end;
			}
			// else {
			// if (msgType.equals("text")) {
			// re = "收到文字";
			// msgtype="text";
			// }
			// if (msgType.equals("image")) {
			// re = "收到图片";
			// msgtype="image";
			//
			// }
			// if (msgType.equals("voice")) {
			// re = "收到声音";
			// msgtype="voice";
			// }
			// }
		} else {
			n = Integer.parseInt(types);
			CacheKit.put("extMap", fromuser + "types", n + 1);
			if (msgType.equals("text")) {
				re = "收到文字";
				msgtype = "text";
			}
			if (msgType.equals("image")) {
				re = "收到图片";
				msgtype = "image";
			}
			if (msgType.equals("voice")) {
				re = "收到声音";
				msgtype = "voice";
			}
		}
		System.out.println("=========re====" + re + "=====" + n);
		n = n + 1;
		content = "<p class='" + msgtype + "'   id= 'text" + n + "'>" + content
				+ "</p>";
		if (CacheKit.get("extMap", fromuser + "content") != null) {
			content = CacheKit.get("extMap", fromuser + "content").toString()
					+ content;
		}
		System.out.println("=========content====" + content);
		CacheKit.put("extMap", fromuser + "content", content);

		OutTextMsg outMsg = new OutTextMsg((InMsg) obj);
		outMsg.setContent(re);
		render(outMsg);

	}

	/**
	 * 选取模板信息
	 */
	public void view() {
		String type = getPara("type");
		String mbmc = "";
		List<Record> mblist = new ArrayList<Record>();
		mblist = CacheKit.get("mblist", "mblist");
		if (mblist == null) {
			mblist = Db.find("Select *  from wx_mb  order by dsporder");
			CacheKit.put("mblist", "mblist", mblist);
		}
		String url = "";
		for (Record n : mblist) {
			if (type.equals(n.get("id").toString())) {
				mbmc = n.get("mbmc");
				url = n.get("mburl");
			}
		}

		if (url != null && !url.substring(0, 1).equals("/")) {
			url = "/" + url;
		}
		// 模板步骤
		List<Record> mbtypelist = mbsx(type);

		String fromuser = getPara("fromuser");
		setAttr("fromuser", fromuser);
		setAttr("mbtypelist", mbtypelist);
		setAttr("type", type);
		setAttr("mbmc", mbmc);
		setAttr("argu", "view");
		render("/WEB-INF/view/weixin/temp" + url);
	}

	/**
	 * 保存模板信息
	 */
	public void savetype() {
		String type = getPara("type");
		String fromuser = getPara("fromuser");
		CacheKit.put("extMap", fromuser, fromuser);
		if (type != null && fromuser != null) {
			CacheKit.put("extMap", fromuser + "template", type);
			CacheKit.put("extMap", fromuser + "types", 0);
			renderJson("选择成功！");
			String typename = "";
			List<Record> mbtypelist = mbsx(type);
			if (mbtypelist != null && mbtypelist.size() > 0) {
				typename = "请输入：" + mbtypelist.get(0).get("mbsxmc");
				// 封装推送数据
				HashMap map = new HashMap();
				map.put("content", typename);
				String json = MsgCustomApi.createCustomJson(fromuser, "text",
						map);
				MsgCustomApi msg = new MsgCustomApi();
				ApiResult apiResult = msg.createCustom(json);
			} else {
				typename = "请输入：文字声音或者图片";
				// 封装推送数据
				HashMap map = new HashMap();
				map.put("content", typename);
				String json = MsgCustomApi.createCustomJson(fromuser, "text",
						map);
				for (int i=0; i<3; i++) {
					 AccessTokenApi.getAccessToken().getAccessToken();
				}
				System.out.println("getAccessToken().getAccessToken()"+ AccessTokenApi.getAccessToken().getAccessToken());

				MsgCustomApi msg = new MsgCustomApi();
				ApiResult apiResult = msg.createCustom(json);
			}

		} else {
			renderJson("选择失败！");
		}
	}

	
	/**
	 * 数据库保存数据 并返回图文消息
	 */
	// @SuppressWarnings({ "unchecked", "rawtypes"})
	public void savemsg(String fromuser) {
		String content = "";
		if (StringKit.notNull(CacheKit.get("extMap", fromuser + "content"))) {
			content = (String) CacheKit.get("extMap", fromuser + "content");
		}

		System.out.println("========content==" + content);

		String type = (String) CacheKit.get("extMap", fromuser + "template");
		String pic = "";
		if (StringKit.notNull(CacheKit.get("extMap", fromuser + "pic"))) {
			pic = (String) CacheKit.get("extMap", fromuser + "pic");
		}
		String title = (String) CacheKit.get("extMap", fromuser + "title");
		String picurl = "";
		if (StringKit.notBlank(pic)) {
			picurl = url.substring(0, url.length() - 1) + "/" + pic;

		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		String date = df.format(new Date());
		WxContent wx = getModel(WxContent.class);
		boolean count = wx.set("title", title).set("fromuser", fromuser)
				.set("type", type).set("content", content).set("picurl", pic)
				.set("date", date).save();
		int id = wx.getInt("id");

		removeAllMap(fromuser);
		HashMap map = new HashMap();
		map.put("title", title);
		map.put("description", "美文制作");
		map.put("url", url + "wxContent?id=" + id + "&from=user");
		map.put("picurl", picurl);
		// 封装推送数据
		String json = MsgCustomApi.createCustomJson(fromuser, "news", map);
		MsgCustomApi msg = new MsgCustomApi();
		ApiResult apiResult = msg.createCustom(json);
		System.out.println("======================" + apiResult.getErrorCode());
		System.out.println("======================" + apiResult.getErrorMsg());
		renderNull();
	}

	/**
	 * 罗列标题和关键字作为帮助消息
	 * 
	 * @return String
	 */
	public void helpString(InFollowEvent inFollowEvent) {
		List<Record> newlist;
		newlist = CacheKit.get("WxMessage", "WxMessage");
		if (newlist == null) {
			newlist = WxMessage.dao.findAlls("");
			// 放入缓存
			CacheKit.put("WxMessage", "WxMessage", newlist);
		}
		for (int i = 0; i < newlist.size(); i++) {
			String msgtype = (String) newlist.get(i).get("msgtype"); // 回复文本类型
			String description = (String) newlist.get(i).get("description"); // 关键字
			String url = (String) newlist.get(i).get("url"); // 消息链接
			String picurl = (String) newlist.get(i).get("picurl"); // 消息图片
			String title = (String) newlist.get(i).get("title"); // 标题
			String content = (String) newlist.get(i).get("content"); // 文本内容
			String yxbz = (String) newlist.get(i).get("yxbz"); // 文本内容
			if (yxbz.equals("1")) {
				if (msgtype.equals("text")) {
					OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
					outMsg.setContent(content);
					render(outMsg);
					// 图文消息
				} else if (msgtype.equals("news")) {
					OutNewsMsg outMsg = new OutNewsMsg(inFollowEvent);
					outMsg.addNews(title, "", picurl, url);
					render(outMsg);
				}
			}
		}
	}

	/**
	 * 客服消息
	 */
	public void renderkf(OutMsg outMsg) {
		String outMsgXml = OutKfXmlBuilder.build(outMsg);
		renderText(outMsgXml, "text/xml");
	}

	/**
	 * 模板选择
	 */
	public void rendermb(Object obj, String fromuser, String i) {
		OutNewsMsg outMsg = new OutNewsMsg((InMsg) obj);
//		if (i.equals("1")) {
//			outMsg.addNews(" 请先选择模板！ ", "", "", "");
//		} else {
//			outMsg.addNews("" + starts + " ", "", "", "");
//		}
		// List<Record> mblist = new ArrayList<Record>();
		// mblist = CacheKit.get("mblist", "mblist");
		//
		// if (mblist == null) {
		// mblist = Db
		// .find("Select *  from wx_mb where yxbz='1'   order by dsporder");
		// CacheKit.put("mblist", "mblist", mblist);
		// }
		// if (mblist != null && mblist.size() > 0) {
		// for (Record n : mblist) {
		outMsg.addNews(" 点击选择模板", " ", "", url + "weixin/viewmb?&openid="
				+ fromuser);
//		outMsg.addNews(" 点击开始制作", " ", "", url + "weixin/savetypecy?type=24&fromuser="
//				+ fromuser);
		// }
		// }
		render(outMsg);
	}

	/**
	 * 数据清除
	 */
	public void removeAllMap(String fromuser) {
		if (CacheKit.get("extMap", fromuser) != null) {
			// extMap.remove(fromuser);
			CacheKit.remove("extMap", fromuser);
		}
		if (CacheKit.get("extMap", fromuser + "title") != null) {
			// extMap.remove(fromuser + "title");
			CacheKit.remove("extMap", fromuser + "title");

		}
		if (CacheKit.get("extMap", fromuser + "template") != null) {
			// extMap.remove(fromuser + "template");
			CacheKit.remove("extMap", fromuser + "template");

		}
		if (CacheKit.get("extMap", fromuser + "content") != null) {
			// extMap.remove(fromuser + "content");
			CacheKit.remove("extMap", fromuser + "content");

		}
		if (CacheKit.get("extMap", fromuser + "types") != null) {
			// extMap.remove(fromuser + "types");
			CacheKit.remove("extMap", fromuser + "types");

		}
		if (CacheKit.get("extMap", fromuser + "pic") != null) {
			// extMap.remove(fromuser + "pic");
			CacheKit.remove("extMap", fromuser + "pic");

		}
	}

	public void findAll(Object obj, String fromuser) {
		List<Record> newlist = WxContent.dao.findAlls("       fromuser=  '"
				+ fromuser + " '", "  limit 0, 8");
		System.out.println("++++++++++++++++++++++" + fromuser);
		OutNewsMsg outMsgs = new OutNewsMsg((InMsg) obj);
		if (newlist.size() > 0) {
			for (int i = 0; i < newlist.size(); i++) {
				String title = newlist.get(i).get("title");
				String picurl = newlist.get(i).get("picurl");
				String type = newlist.get(i).get("type").toString();
				String id = newlist.get(i).get("id").toString();
				String yxbz=newlist.get(i).get("yxbz").toString();
				if (StringKit.notBlank(picurl)) {
					picurl = url + picurl;
				}
				String urls="";
				System.out.println("==========="+yxbz);
				if(!yxbz.equals("1")){
					 urls = url + "wxContent/view/" + id ;
				}else{
				//	 urls = url + "wxContent/editcy?type=" + type + "&fromuser="+fromuser+"&id="+id;
					 urls = url + "wxContent/view/"+id;

				}
				outMsgs.addNews(title, "微文制作", picurl, urls);
			}
			outMsgs.addNews("更多", "微文制作", "", url + "wxContent/more?fromuser="
					+ fromuser);
			render(outMsgs);
		} else {
			OutTextMsg outMsg = new OutTextMsg((InMsg) obj);
			outMsg.setContent(helpStr);
			render(outMsg);
		}
	}
	
	/**
	 * 保存初页模板信息
	 */
	@Before(WxInterceptor.class)
	public void savetypecy() {
		String type = getPara("type");
		String fromuser = getPara("fromuser");
		Record xx = new Record();
		List<Record> mblist = Db.find("select * from wx_mb where id=?", type);
		System.out.println("mblist++++++++++++++++++"+mblist);

		String viewurls="";
		String viewmb="0";
		String mblx="";
		viewmb=mblist.get(0).getStr("viewmb");
		viewurls=mblist.get(0).get("mburl");
		if (viewurls != null && !viewurls.substring(0, 1).equals("/")) {
			viewurls = "/" + viewurls;
		}
		mblx=mblist.get(0).getStr("mblx");
		System.out.println("mblist.get(0)"+mblist.get(0).get("mbmc"));
//		xx.set("type", type).set("fromuser", fromuser).set("yxbz", "1")
//				.set("title","我的"+ mblist.get(0).get("mbmc")).set("picurl", mblist.get(0).get("picurl"));
//		Db.save("wx_content", xx);
//		List<Record> mbsxlist = Db.find(
//				"select * from wx_mbsx where type='img'  and lbid=?", type);
		String urls = url + "weixin/savetypecy?type=" + type + "&fromuser="+ fromuser;
		String urla="";
		if(url.endsWith("/")){
			urla=url.substring(0,url.length()-1)+getAttr("wxurls").toString();
		}
		else {
			urla=url+getAttr("wxurls").toString();
		}
		System.out.println("savetypecy++++++++++++++++++"+urla);
		Map map = CheckJs.setsign(urls);
		setAttr("appId", AppId);
		setAttr("timestamp", map.get("timestamp"));
		setAttr("nonceStr", map.get("nonceStr"));
		setAttr("signature", map.get("signature"));
//    setAttr("mbsxlist", mbsxlist);
		setAttr("mblist", mblist);
		setAttr("fromuser", fromuser);
//    setAttr("contentid", xx.get("id"));
		setAttr("argu", "edit");
		setAttr("viewmb",viewmb);
		setAttr("type",type);
		System.out.println("viewmb++++++++++++++++++"+viewmb);

		if(mblx.equals("1")){
			if(StringKit.notBlank(viewmb) ){
				if(viewmb.equals("1")){
					render("/WEB-INF/view/weixin/temp/"+viewurls);
				}
			}else {
				render("/WEB-INF/view/weixin/temp/cy.html");
			}
		} else {
			render("/WEB-INF/view/weixin/temp/temp.html");
		}
	
	}


	public List<Record> mbsx(String type) {
		List<Record> mbtypelist = new ArrayList<Record>();
		mbtypelist = CacheKit.get("mbtypelist", "mbtypelist" + type);
		if (mbtypelist == null) {
			mbtypelist = Db.find("Select *  from wx_mbsx where  lbid ='" + type
					+ "'  order by dsporder");
			CacheKit.put("mbtypelist", "mbtypelist" + type, mbtypelist);
		}
		return mbtypelist;
	}

	public String getopendid(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code";
		url = url.replace("AppId", AppId).replace("AppSecret", AppSecret)
				.replace("CODE", code);
		String jsonResult = HttpKit.get(url);
		JSONObject jsonTexts = (JSONObject) JSON.parse(jsonResult);
		String openid = "";
		if (StringKit.notNull(jsonTexts.get("openid"))) {
			openid = jsonTexts.get("openid").toString();
		}
		System.out.println("===============" + openid);

		return openid;
	}

	public void viewmb() {
		String code = getPara("code");
		String openid = "";
		if (StringKit.notBlank(getPara("openid"))) {
			openid = getPara("openid");
		} else {

		if (StringKit.notBlank(getCookie("openidpyq"))) {
			openid = getCookie("openidpyq");
			System.out.println("---------------------------cookie get openid"
					+ getCookie("openidpyq"));
		} else {
			if (StringKit.notBlank(code)) {
				openid = getopendid(code);
				setCookie("openidpyq", openid, 3600 * 24 * 10);
			}
		}
	}

		List<Record> mblist = new ArrayList<Record>();
		mblist = CacheKit.get("mblist", "mblist");

		if (mblist == null) {
			mblist = Db.find("Select *  from wx_mb where yxbz='1'   order by dsporder");
			CacheKit.put("mblist", "mblist", mblist);
		}

		setAttr("appId", AppId);
		setAttr("mblist", mblist);
		setAttr("openid", openid);
		render("/WEB-INF/view/weixin/temp/indexs.html");
	}

	
	public void viewmore() {
		String code = getPara("code");
		String openid = "";
		if (StringKit.notBlank(getPara("openid"))) {
			openid = getPara("openid");
		} else {

		if (StringKit.notBlank(getCookie("openidpyq"))) {
			openid = getCookie("openidpyq");
			System.out.println("---------------------------cookie get openid"
					+ getCookie("openidpyq"));
		} else {
			if (StringKit.notBlank(code)) {
				openid = getopendid(code);
				setCookie("openidpyq", openid, 3600 * 24 * 10);
			}
		}
	}

		List<Record> newlist = WxContent.dao.findAlls(" fromuser=  '"
				+ openid + "'", "");
		setAttr("newlist", newlist);
		
		setAttr("appId", AppId);
		setAttr("openid", openid);
		render("/WEB-INF/view/weixin/temp/more.html");
		}

}
